<?php
namespace Home\Controller;
use Think\Controller;
class ShoppingController extends Controller {
	public function __construct(){
		parent::__construct();
		if(!$_SESSION['user_is_login']){
			$this->error("没有登录，请用户去登录。",U("Home/user/login"));
		}
	}
	public function addToCart(){
		$user_id = $_SESSION['user_id'];
		$product_id = I('post.product_id');
		$num = I('post.num');
		$where=array('user_id' => $user_id ,'product_id' => $product_id);
		if ($cart=M('user_cart')->where($where)->find()) {
			M('user_cart')->where($where)->save(array("num" => $num+$cart['num']));
		}else{
			M('user_cart')->add(array('user_id' => $user_id,'product_id' => $product_id,'num' => $num));
		}
		$this->success("添加购物车成功!",U("Home/product/detail/id/".$product_id));
	}
	public function cartlist(){
		$carts=M('user_cart')->where('user_id ='.$_SESSION['user_id'])->select();
		$this->assign('carts',$carts);
		$this->display();
	}
	public function cartdel($id){
		M('user_cart')->where('id ='.$id)->delete();
		$this->redirect('Home/Shopping/cartlist');
	}
	public function updateCart(){
		$id = I('get.id');
		$num = I('get.num');
		if($num > 0){
			M('user_cart')->where('id ='.$id)->save(array('num' => $num));
			echo "ok";
		}else{
			echo "数量不能小于0";
		}
	}
	public function cartdels(){
		$ids = I('post.ids');
		M('user_cart')->delete(implode(',',$ids));
		$this->redirect('Home/Shopping/cartlist');
	}
	public function preOrder(){
		$data = I('post.data');
		if (count($data) == 0) {
			echo "请选择一个商品！";
		}else{
			$_SESSION['preorder'] = $data;
			echo "ok";
		}
	}
	public function createOrder(){
		$address=M('user_adderss')->where('user_id ='.$_SESSION['user_id'])->select();
		$this->assign('address',$_SESSION['preorder']);
		$this->assign('data',$data);
		$this->display();
	}
	public function do_createOrder(){
		$address_id = I('post.address_id');
		if(!$address_id){
			$this->error('请选择一个收货地址');
		}
		$order_id=M("orders")->add(array(
			'user_id'=>$_SESSION['user_id'],
			'address_id'=>$address_id,
			'create_time'=>time(),
			'status'=>0
		));
		$product_id = I('post.product_id');
		$num = I('post.num');
		$count = count($product_id);
		for($i=0;$i<$count;$i++){
			M("orders_product")->add(array(
				'order_id'=>$order_id,
				'product_id'=>$product_id[$i],
				'num'=>$num[$i],
			));
		}
		$this->success('订单提交成功！',U('home/front/index'));
	}
	public function addAddress(){
		$name = I('post.name');
		$address = I('post.address');
		$phone = I('post.phone');
		if (empty($name)) {
			echo json_encode(array('code' => 'error','field' => 'name','msg' => '姓名不能为空'));
			exit();
		}
		if (empty($address)) {
			echo json_encode(array('code' => 'error','field' => 'address','msg' => '姓名不能为空'));
			exit();
		}
		M('user_adderss')->add(array('name' => $name,'address' => $address,'user_id' => $_SESSION['user_id'],'phone' => $phone,));
		echo json_encode(array('code' => 'ok'));
	}
}